<template>
  <div
    ref="swiper"
    class="swiper"
    style="overflow: hidden"
    @mouseenter="swiperMouseEnter"
    @mouseleave="swiperMouseLeave"
  >
    <div class="swiper-wrapper" aria-live="polite">
      <div v-for="(item, index) of dataList" :key="item[keyField] || index" class="swiper-slide">
        <slot :scope="item" :index="index" />
      </div>
    </div>
  </div>
</template>

<script>
import Swiper, { Autoplay } from 'swiper';
Swiper.use([Autoplay]);

export default {
  name: 'VueSwiper',
  props: {
    dataList: { type: Array, default: () => [] },
    keyField: { type: String, default: 'id' },
    swiperOptions: { type: Object, default: () => ({}) },
  },
  data() {
    return {};
  },
  computed: {
    options() {
      const option = Object.assign(
        {
          direction: 'vertical', // horizontal,vertical
          loop: true,
          slidesPerView: 1,
          spaceBetween: 0,
          centeredSlides: false, //这个居中会导致分割现象
          observe: true,
          observeParents: true,
          observeSlideChildren: true,
        },
        this.swiperOptions
      );
      if (typeof option.autoplay !== 'boolean') {
        option.autoplay = Object.assign(
          {
            delay: 6 * 1000,
            pauseOnMouseEnter: true,
            stopOnLastSlide: false,
            disableOnInteraction: false,
          },
          option.autoplay
        );
      }
      return option;
    },
  },
  unmounted() {
    this.destroy();
  },
  mounted() {
    this.$watch(
      () => this.options,
      () => {
        if (this.swiper) {
          this.swiper.destroy();
        }
        this.swiper = new Swiper(this.$refs.swiper, this.options);
      },
      { immediate: true }
    );
    Object.keys(this.$attrs).forEach((key) => {
      if (/^on[A-z]/.test(key) && typeof this.$attrs[key] === 'function') {
        this.swiper.on(key, this.$attrs[key]);
      }
    });
    this.$emit('ready', this.swiper);
  },
  methods: {
    swiperMouseEnter() {
      this.swiper.autoplay.stop();
    },
    swiperMouseLeave() {
      this.swiper.autoplay.start();
    },
    destroy() {
      if (this.swiper) {
        this.swiper.destroy();
      }
    },
  },
};
</script>

<style lang="less">
//@import '~swiper/swiper.min.css';
.swiper {
  width: 100%;
  height: 100%;
  .swiper-wrapper {
    width: 100%;
    height: 100%;
    .swiper-slide {
      /* Center slide text vertically */
      display: -webkit-box;
      display: -ms-flexbox;
      display: -webkit-flex;
      display: flex;
      -webkit-box-pack: center;
      -ms-flex-pack: center;
      -webkit-justify-content: center;
      justify-content: center;
      -webkit-box-align: center;
      -ms-flex-align: center;
      -webkit-align-items: center;
      align-items: center;
      width: 100%;
      height: 100%;
    }
  }
}
</style>
